<template>
  <div class="duration-selector">
    <div class="selector-header">
      <h3 class="title">
        <i class="fas fa-clock"></i>
        症状持续时间
      </h3>
      <p class="subtitle">请选择症状开始时间和持续情况</p>
    </div>

    <!-- 快速选择 -->
    <div class="quick-duration-section">
      <h4 class="section-title">
        <i class="fas fa-bolt"></i>
        快速选择
      </h4>
      <div class="quick-options">
        <el-button
          v-for="option in quickOptions"
          :key="option.value"
          :type="selectedQuickOption === option.value ? 'primary' : 'default'"
          @click="selectQuickOption(option)"
          class="quick-option-btn"
        >
          <i :class="option.icon"></i>
          {{ option.label }}
        </el-button>
      </div>
    </div>

    <!-- 精确时间选择 -->
    <div class="precise-duration-section">
      <h4 class="section-title">
        <i class="fas fa-calendar-alt"></i>
        精确时间
      </h4>
      
      <div class="time-inputs">
        <!-- 开始时间 -->
        <div class="time-input-group">
          <label class="input-label">
            <i class="fas fa-play"></i>
            症状开始时间
          </label>
          <div class="datetime-container">
            <el-date-picker
              v-model="startDateTime"
              type="datetime"
              placeholder="选择开始时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="updateDuration"
              :disabled-date="disabledStartDate"
              class="datetime-picker"
            />
          </div>
        </div>

        <!-- 结束时间或持续状态 -->
        <div class="time-input-group">
          <label class="input-label">
            <i class="fas fa-stop"></i>
            结束时间
          </label>
          <div class="end-time-container">
            <el-radio-group v-model="endTimeType" @change="updateDuration" class="end-type-radio">
              <el-radio label="ongoing">仍在持续</el-radio>
              <el-radio label="ended">已结束</el-radio>
            </el-radio-group>
            
            <el-date-picker
              v-if="endTimeType === 'ended'"
              v-model="endDateTime"
              type="datetime"
              placeholder="选择结束时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="updateDuration"
              :disabled-date="disabledEndDate"
              class="datetime-picker"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 持续时间显示 -->
    <div class="duration-display" v-if="calculatedDuration">
      <h4 class="section-title">
        <i class="fas fa-hourglass-half"></i>
        持续时间统计
      </h4>
      <div class="duration-stats">
        <div class="duration-card">
          <div class="duration-value">{{ calculatedDuration.total }}</div>
          <div class="duration-label">总持续时间</div>
        </div>
        <div class="duration-breakdown">
          <div class="breakdown-item" v-if="calculatedDuration.days > 0">
            <span class="breakdown-value">{{ calculatedDuration.days }}</span>
            <span class="breakdown-unit">天</span>
          </div>
          <div class="breakdown-item" v-if="calculatedDuration.hours > 0">
            <span class="breakdown-value">{{ calculatedDuration.hours }}</span>
            <span class="breakdown-unit">小时</span>
          </div>
          <div class="breakdown-item" v-if="calculatedDuration.minutes > 0">
            <span class="breakdown-value">{{ calculatedDuration.minutes }}</span>
            <span class="breakdown-unit">分钟</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 症状模式分析 -->
    <div class="pattern-analysis" v-if="hasPatternData">
      <h4 class="section-title">
        <i class="fas fa-chart-line"></i>
        症状模式
      </h4>
      <div class="pattern-options">
        <el-checkbox-group v-model="symptomPatterns" @change="updatePatterns">
          <div class="pattern-grid">
            <el-checkbox 
              v-for="pattern in patternOptions" 
              :key="pattern.value"
              :label="pattern.value"
              :value="pattern.value"
              class="pattern-checkbox"
            >
              <div class="pattern-item">
                <i :class="pattern.icon"></i>
                <span>{{ pattern.label }}</span>
              </div>
            </el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
    </div>

    <!-- 时间线可视化 -->
    <div class="timeline-visualization" v-if="showTimeline">
      <h4 class="section-title">
        <i class="fas fa-timeline"></i>
        症状时间线
      </h4>
      <div class="timeline-container">
        <div class="timeline">
          <div class="timeline-item start">
            <div class="timeline-marker start-marker">
              <i class="fas fa-play"></i>
            </div>
            <div class="timeline-content">
              <div class="timeline-time">{{ formatDateTime(startDateTime) }}</div>
              <div class="timeline-label">症状开始</div>
            </div>
          </div>
          
          <div class="timeline-line" :class="{ ongoing: endTimeType === 'ongoing' }"></div>
          
          <div class="timeline-item end" v-if="endTimeType === 'ended'">
            <div class="timeline-marker end-marker">
              <i class="fas fa-stop"></i>
            </div>
            <div class="timeline-content">
              <div class="timeline-time">{{ formatDateTime(endDateTime) }}</div>
              <div class="timeline-label">症状结束</div>
            </div>
          </div>
          
          <div class="timeline-item ongoing" v-else>
            <div class="timeline-marker ongoing-marker">
              <i class="fas fa-ellipsis-h"></i>
            </div>
            <div class="timeline-content">
              <div class="timeline-time">{{ formatDateTime(new Date()) }}</div>
              <div class="timeline-label">仍在持续</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 相关因素记录 -->
    <div class="related-factors">
      <h4 class="section-title">
        <i class="fas fa-lightbulb"></i>
        相关因素
      </h4>
      <div class="factors-input">
        <el-input
          v-model="relatedFactors"
          type="textarea"
          :rows="3"
          placeholder="请记录可能的诱发因素、缓解方式、环境变化等..."
          @input="updateFactors"
          maxlength="300"
          show-word-limit
          class="factors-textarea"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElButton, ElDatePicker, ElRadioGroup, ElRadio, ElCheckboxGroup, ElCheckbox, ElInput } from 'element-plus'

// Props
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({
      startTime: null,
      endTime: null,
      isOngoing: false,
      patterns: [],
      relatedFactors: ''
    })
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'change'])

// 响应式数据
const selectedQuickOption = ref('')
const startDateTime = ref(props.modelValue.startTime || null)
const endDateTime = ref(props.modelValue.endTime || null)
const endTimeType = ref(props.modelValue.isOngoing ? 'ongoing' : 'ended')
const symptomPatterns = ref(props.modelValue.patterns || [])
const relatedFactors = ref(props.modelValue.relatedFactors || '')

// 快速选择选项
const quickOptions = ref([
  { label: '刚刚开始', value: 'just_started', duration: 0, icon: 'fas fa-play' },
  { label: '几分钟前', value: 'few_minutes', duration: 10, icon: 'fas fa-clock' },
  { label: '半小时前', value: 'half_hour', duration: 30, icon: 'fas fa-clock' },
  { label: '1小时前', value: 'one_hour', duration: 60, icon: 'fas fa-clock' },
  { label: '今天早上', value: 'this_morning', duration: null, icon: 'fas fa-sun' },
  { label: '昨天', value: 'yesterday', duration: null, icon: 'fas fa-calendar-day' },
  { label: '几天前', value: 'few_days', duration: null, icon: 'fas fa-calendar-week' },
  { label: '一周前', value: 'one_week', duration: null, icon: 'fas fa-calendar-week' },
  { label: '更早', value: 'earlier', duration: null, icon: 'fas fa-history' }
])

// 症状模式选项
const patternOptions = ref([
  { label: '间歇性发作', value: 'intermittent', icon: 'fas fa-wave-square' },
  { label: '逐渐加重', value: 'worsening', icon: 'fas fa-arrow-trend-up' },
  { label: '逐渐减轻', value: 'improving', icon: 'fas fa-arrow-trend-down' },
  { label: '时好时坏', value: 'fluctuating', icon: 'fas fa-arrows-up-down' },
  { label: '夜间加重', value: 'nocturnal', icon: 'fas fa-moon' },
  { label: '活动后加重', value: 'activity_related', icon: 'fas fa-running' },
  { label: '休息后缓解', value: 'rest_relief', icon: 'fas fa-bed' },
  { label: '药物缓解', value: 'medication_relief', icon: 'fas fa-pills' }
])

// 计算属性
const calculatedDuration = computed(() => {
  if (!startDateTime.value) return null
  
  const start = new Date(startDateTime.value)
  const end = endTimeType.value === 'ongoing' ? new Date() : new Date(endDateTime.value || new Date())
  
  if (end <= start) return null
  
  const diffMs = end - start
  const diffMinutes = Math.floor(diffMs / (1000 * 60))
  const diffHours = Math.floor(diffMinutes / 60)
  const diffDays = Math.floor(diffHours / 24)
  
  const remainingHours = diffHours % 24
  const remainingMinutes = diffMinutes % 60
  
  let totalText = ''
  if (diffDays > 0) {
    totalText = `${diffDays}天${remainingHours}小时`
  } else if (diffHours > 0) {
    totalText = `${diffHours}小时${remainingMinutes}分钟`
  } else {
    totalText = `${diffMinutes}分钟`
  }
  
  return {
    total: totalText,
    days: diffDays,
    hours: remainingHours,
    minutes: remainingMinutes,
    totalMinutes: diffMinutes
  }
})

const hasPatternData = computed(() => {
  return startDateTime.value && calculatedDuration.value && calculatedDuration.value.totalMinutes > 30
})

const showTimeline = computed(() => {
  return startDateTime.value !== null
})

// 方法
const selectQuickOption = (option) => {
  selectedQuickOption.value = option.value
  const now = new Date()
  
  switch (option.value) {
    case 'just_started':
      startDateTime.value = now.toISOString().slice(0, 19).replace('T', ' ')
      endTimeType.value = 'ongoing'
      break
    case 'few_minutes':
      startDateTime.value = new Date(now - option.duration * 60000).toISOString().slice(0, 19).replace('T', ' ')
      endTimeType.value = 'ongoing'
      break
    case 'half_hour':
    case 'one_hour':
      startDateTime.value = new Date(now - option.duration * 60000).toISOString().slice(0, 19).replace('T', ' ')
      endTimeType.value = 'ongoing'
      break
    case 'this_morning':
      const morning = new Date(now)
      morning.setHours(8, 0, 0, 0)
      startDateTime.value = morning.toISOString().slice(0, 19).replace('T', ' ')
      endTimeType.value = 'ongoing'
      break
    case 'yesterday':
      const yesterday = new Date(now - 24 * 60 * 60 * 1000)
      yesterday.setHours(12, 0, 0, 0)
      startDateTime.value = yesterday.toISOString().slice(0, 19).replace('T', ' ')
      endTimeType.value = 'ongoing'
      break
    case 'few_days':
      const fewDays = new Date(now - 3 * 24 * 60 * 60 * 1000)
      fewDays.setHours(12, 0, 0, 0)
      startDateTime.value = fewDays.toISOString().slice(0, 19).replace('T', ' ')
      endTimeType.value = 'ongoing'
      break
    case 'one_week':
      const oneWeek = new Date(now - 7 * 24 * 60 * 60 * 1000)
      oneWeek.setHours(12, 0, 0, 0)
      startDateTime.value = oneWeek.toISOString().slice(0, 19).replace('T', ' ')
      endTimeType.value = 'ongoing'
      break
  }
  
  updateDuration()
}

const disabledStartDate = (date) => {
  return date > new Date()
}

const disabledEndDate = (date) => {
  if (!startDateTime.value) return date > new Date()
  return date < new Date(startDateTime.value) || date > new Date()
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const updateDuration = () => {
  emitUpdate()
}

const updatePatterns = () => {
  emitUpdate()
}

const updateFactors = () => {
  emitUpdate()
}

const emitUpdate = () => {
  const value = {
    startTime: startDateTime.value,
    endTime: endTimeType.value === 'ended' ? endDateTime.value : null,
    isOngoing: endTimeType.value === 'ongoing',
    patterns: symptomPatterns.value,
    relatedFactors: relatedFactors.value,
    duration: calculatedDuration.value
  }
  
  emit('update:modelValue', value)
  emit('change', value)
}

// 监听props变化
watch(() => props.modelValue, (newValue) => {
  if (newValue) {
    startDateTime.value = newValue.startTime || null
    endDateTime.value = newValue.endTime || null
    endTimeType.value = newValue.isOngoing ? 'ongoing' : 'ended'
    symptomPatterns.value = newValue.patterns || []
    relatedFactors.value = newValue.relatedFactors || ''
  }
}, { deep: true })
</script>

<style scoped>
.duration-selector {
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.selector-header {
  text-align: center;
  margin-bottom: 25px;
}

.title {
  color: #2c5aa0;
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.subtitle {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.section-title {
  color: #2c5aa0;
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 15px 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.quick-duration-section {
  margin-bottom: 25px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #52c41a;
}

.quick-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.quick-option-btn {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 6px;
}

.precise-duration-section {
  margin-bottom: 25px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #2c5aa0;
}

.time-inputs {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.time-input-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.input-label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.datetime-container,
.end-time-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.end-type-radio {
  margin-bottom: 10px;
}

.datetime-picker {
  width: 100%;
}

.duration-display {
  margin-bottom: 25px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
}

.duration-display .section-title {
  color: white;
}

.duration-stats {
  display: flex;
  align-items: center;
  gap: 20px;
}

.duration-card {
  text-align: center;
}

.duration-value {
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 5px;
}

.duration-label {
  font-size: 14px;
  opacity: 0.9;
}

.duration-breakdown {
  display: flex;
  gap: 15px;
}

.breakdown-item {
  text-align: center;
  padding: 10px 15px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 8px;
}

.breakdown-value {
  display: block;
  font-size: 18px;
  font-weight: 600;
}

.breakdown-unit {
  font-size: 12px;
  opacity: 0.8;
}

.pattern-analysis {
  margin-bottom: 25px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #faad14;
}

.pattern-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
}

.pattern-checkbox {
  margin: 0;
}

.pattern-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.pattern-checkbox:hover .pattern-item {
  background: #e6f7ff;
}

.timeline-visualization {
  margin-bottom: 25px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #722ed1;
}

.timeline-container {
  padding: 20px 0;
}

.timeline {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.timeline-item {
  display: flex;
  align-items: center;
  gap: 15px;
  margin: 10px 0;
}

.timeline-marker {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
}

.start-marker {
  background: #52c41a;
}

.end-marker {
  background: #f5222d;
}

.ongoing-marker {
  background: #faad14;
  animation: pulse 2s infinite;
}

.timeline-line {
  width: 4px;
  height: 60px;
  background: #d9d9d9;
  margin: 5px 0;
}

.timeline-line.ongoing {
  background: linear-gradient(to bottom, #d9d9d9 0%, #faad14 100%);
  animation: flow 2s infinite;
}

.timeline-content {
  text-align: center;
}

.timeline-time {
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.timeline-label {
  font-size: 12px;
  color: #666;
}

.related-factors {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #13c2c2;
}

.factors-textarea {
  margin-top: 10px;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.6; }
  100% { opacity: 1; }
}

@keyframes flow {
  0% { background-position: 0% 0%; }
  100% { background-position: 0% 100%; }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .duration-selector {
    padding: 15px;
  }
  
  .quick-options {
    justify-content: center;
  }
  
  .quick-option-btn {
    font-size: 12px;
    padding: 6px 12px;
  }
  
  .time-inputs {
    grid-template-columns: 1fr;
  }
  
  .duration-stats {
    flex-direction: column;
    gap: 15px;
  }
  
  .duration-breakdown {
    justify-content: center;
  }
  
  .pattern-grid {
    grid-template-columns: 1fr;
  }
}
</style>